<?php
namespace app\mobile\controller;

use app\model\Record; 
use app\model\Util; 
use app\model\Theme; 
use app\model\Worker; 
use app\model\Fans; 
use app\model\Order; 

class WOrderedit extends Base
{
    public function W_orderedit()
    {
global $_G, $_P;
$fans = $this->checkuser();
$themeid = intval($_P['themeid']);
if($themeid < 0){
	return_msg('管理后台地址不正确');
}
$system=$_G['system'];
$theme = Theme::getThemeById($themeid);
$config = 	Theme::getConfig($themeid);
if(empty($theme['id'])){
	return_msg('管理后台地址不正确');
}
$myworker = Worker::getThemeWorkerByOpenidNew($_G['openid'],$themeid);
if(!($system['ruanjian']!=3 || $config['showshop']==0 || ($system['ruanjian']==3 && $config['showshop']==$myworker['company']))){
	$myworker = "";
}
if (empty($myworker)) {
	return_msg('您不是员工,无权访问');
}
$msg = Worker::gethoutaistats();
if (!empty($msg)) {
	return_msg($msg);
}
$do = 'order';
$op = !empty($_P['op']) ? $_P['op'] : 'display';
$id = intval($_P['id']);
if($op == 'searchtuan') {
    $result = Record::searchtuan($themeid);
    return_msg($result, '', 'ajax');
}
if ($op=='display') {
    if ($system['softstyle']==5) {
        $tuanzhang = $config['jmbiemingwenzi'];
        $danmai = $config['jmbiemingwenzi2'];
    }else{
        $tuanzhang = '团长';
        $danmai = '单买'; 
    }

    $uid = intval($_P['uid']);
    if($uid != 0) {
        $fansinfo = db_find('SELECT * FROM ' . tablename(t_fans) . ' 
            WHERE themeid = :themeid AND uid = :uid', array(':themeid' => $themeid,':uid' => $uid));
    }
    if($id == 0) {
        return_tips('定单信息不存在', $url, 'success');
    }
    $record = db_find('SELECT * FROM ' . tablename(t_record) . ' 
            WHERE themeid = :themeid AND id = :id', array(':themeid' => $themeid,':id' => $id));
    if ($record['type']==0 ) {
        $record['pid'] = $record['id'];
    }

    if(empty($record)) {
        return_tips('定单信息不存在', $url, 'success');
    }

    $tuanlist = db_select("SELECT r.id,r.username,r.mobile FROM " . tablename ( t_record ) . " as r
        left join " . tablename ( t_worker ) . ' as w on r.workerid = w.uid and r.themeid = w.themeid 
        WHERE r.id = ' . $record['pid'] .' order by r.mobile asc');

    foreach ($tuanlist as $index => $item) {
        $tuanlist[$index]['renshu'] = Record::getAttendDetailNumByPId($item['id'])+1;
    }

    $sql = 'SELECT w.*,t.name as teamname,s.name as companyname FROM ' . tablename(t_worker) . " as w 
            left join " . tablename ( t_team ) . " as t on w.team = t.id
            left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
            WHERE w.themeid = :themeid
            ORDER BY company,team,uid  ";
    $wlist = db_select($sql, array(":themeid"=>$themeid));
    
}elseif ($op=='save'){

    $record = db_find('SELECT * FROM ' . tablename(t_record) . ' 
            WHERE themeid = :themeid AND id = :id', array(':themeid' => $themeid,':id' => $id));
    if ($record['type']==0 ) {
        $record['pid'] = $record['id'];
    }
        $opuser = $myworker['username'];
        if ($config['iseditorder']==1 || $myworker['level'] == '1') {
            $data = array(
                    'username' => trim($_P['username']),
                    'mobile' => trim($_P['mobile']),
                    'option' => $_P['shoptitle'],
                    'address' => $_P['address_ordernew'],
                    'datetime' => $_P['date_ordernew'],
                ); 

            $beizhu = $record['beizhu']; 
            if ($data['username']!=$record['username']) {
                $beizhu .= date('m-d H:i') . ' ' . $config['nametext'] . '：'.$record['username'].' 改为 ' . $data['username'] . ' 操作:' . $opuser . '<br>';
            }
            if ($data['mobile']!=$record['mobile']) {
                $beizhu .= date('m-d H:i') . ' ' . $config['mobiletext'] . '：'.$record['mobile'].' 改为 ' . $data['mobile'] . ' 操作:' . $opuser . '<br>';
            }
            if ($data['option']!=$record['option']) {
                $beizhu .= date('m-d H:i') . ' ' . $config['shops'] . '：'.$record['option'].' 改为 ' . $data['option'] . ' 操作:' . $opuser . '<br>';
            }
            if ($data['address']!=$record['address']) {
                $beizhu .= date('m-d H:i') . ' ' . $config['address'] . '：'.$record['address'].' 改为 ' . $data['address'] . ' 操作:' . $opuser . '<br>';
            }
            if ($data['datetime']!=$record['datetime']) {
                $beizhu .= date('m-d H:i') . ' ' . $config['datetime'] . '：'.$record['datetime'].' 改为 ' . $data['datetime'] . ' 操作:' . $opuser . '<br>';
            }
        }

        if ($myworker['level'] == '1'){

            $workerid = $_P['workerid'];
            $iszhixiao="";
            if ($workerid != $record['workerid'] ){
                $data['workerid'] = $workerid;
                if ($system['hdget']==1 &&Fans::getuid_old($workerid,$themeid)) {
                    $data['workerid_old']  = $workerid;
                }
                $tempa = Worker::getThemeWorkerNameByUid($record['workerid'],$themeid,$system['ruanjian']);
                $tempb = Worker::getThemeWorkerNameByUid($workerid,$themeid,$system['ruanjian']);
                $beizhu .= date('m-d H:i') . ' 所属员工：'. $tempa .' 改为 ' . $tempb . ' 操作:' . $opuser . '<br>';
                //更新日报表
                if ($record['status']==3) {
                    if ($workerid ==$record['fromuid']) {
                        $zhixiao ="recordxx = recordxx +1,";
                    }
                    db_query("UPDATE ".tablename(t_workerreport)." SET recordxx = recordxx + 1," . $zhixiao . "fee = fee + " . $record['fee'] . " WHERE themeid =:themeid and workerid =:workerid and riqi =:riqi" ,array(":themeid"=>$themeid,':workerid' => $workerid,':riqi' => date("Y-m-d",$record['addtime'])));
                    if ($record['workerid']==$record['fromuid']) {
                        $iszhixiao ="recordxx = recordxx -1,";
                    }
                    db_query("UPDATE ".tablename(t_workerreport)." SET recordxx = recordxx -1," . $iszhixiao . " fee = fee - " . $record['fee'] . " WHERE themeid =:themeid and workerid =:workerid and riqi =:riqi" ,array(":themeid"=>$themeid,':workerid' => $record['workerid'],':riqi' => date("Y-m-d",$record['addtime'])));
                }else{
                    if ($workerid ==$record['fromuid']) {
                        $zhixiao ="recordxx = recordxx +1,";
                    }
                    db_query("UPDATE ".tablename(t_workerreport)." SET record = record +1," . $zhixiao . "fee = fee + " . $record['fee'] . " WHERE themeid =:themeid and workerid =:workerid and riqi =:riqi" ,array(":themeid"=>$themeid,':workerid' => $workerid,':riqi' => date("Y-m-d",$record['addtime'])));
                    if ($record['workerid']==$record['fromuid']) {
                        $iszhixiao ="recordxx = recordxx -1,";
                    }
                    db_query("UPDATE ".tablename(t_workerreport)." SET record = record -1," . $iszhixiao . " fee = fee - " . $record['fee'] . " WHERE themeid =:themeid and workerid =:workerid and riqi =:riqi" ,array(":themeid"=>$themeid,':workerid' => $record['workerid'],':riqi' => date("Y-m-d",$record['addtime'])));
                }
                Theme::renewworkreport($themeid,$workerid);
                Theme::renewworkreport($themeid,$record['workerid']);
            }
        }

        if ($config['iseditorder']==1 || $myworker['level'] == '1') {
            $tuanid = $_P['tuanid'];
            if ($tuanid != $record['pid'] && $config['maxcountall']>1){
                $data['pid'] = $tuanid;
                $data['type'] = 1;
                $tempa = $record['pid']+10000;
                $tempb = $tuanid+10000;
                if ($record['type']==0){
                    $shenfen = $tuanzhang;
                }elseif ($record['type']==1){
                    $shenfen = '团员';
                }elseif ($record['type']==9){
                    $shenfen = $danmai;
                }
                $beizhu .= date('m-d H:i') . ' 所属团：'. $tempa . $shenfen .' 改为 ' . $tempb . '团员 操作:' . $opuser . '<br>';
            }
        }
        $data['beizhu'] = $beizhu;
        db_update(t_record, $data, array('id' => $_P['id']));

        if ($config['iseditorder']==1 || $myworker['level'] == '1') {
            //更新团状态
            if ($tuanid != $record['pid'] && $config['maxcountall']>1){
                $count = Record::getAttendDetailNumByPId($record['pid']);
                db_update( t_record, array("tuannum"=>$count+1), array ('pid' => $record['pid']) );
                if ($record['renshu']==1) {
                    $neednum = intval($config['maxcountall2'])-1;
                }else{
                    $neednum = intval($config['maxcountall'])-1;
                }
                if($count >= $neednum){
                    Record::setIsfinish($record['pid']);
                }else{
                    Record::setNofinish($record['pid']);
                }
                if ($record['type']==0){
                    $sql = "SELECT ord.* FROM " . tablename ( t_record ) . " as ord
                                WHERE  ord.themeid ='{$themeid}' 
                                and (status > 0 or status = -2) and type = 1 and ord.pid='{$record['pid']}' 
                                ORDER BY ord.addtime asc ";
                    $list = db_find ( $sql,$params);
                    if (!empty($list)){
                        $beizhu = $list['beizhu'];
                        $beizhu .= date('m-d H:i') . ' 因团长【'.$record['username'].'】转走，成为新团长 操作:' . $opuser . '<br>';
                        $state = db_update(t_record, array('type' => 0,'beizhu'=>$beizhu), array('id' => $list['id']));
                        $state = db_update(t_record, array('pid' => $list['id']), array('pid' => $record['pid']));
                        $state = db_update(t_order, array('ordertype' => 0), array('masterid' => $list['id'],'ordertype' => 1));
                        
                    }
                }

                $count = Record::getAttendDetailNumByPId($tuanid);
                db_update( t_record, array("tuannum"=>$count+1), array ('pid' => $tuanid) );
                if ($record['renshu']==1) {
                    $neednum = intval($config['maxcountall2'])-1;
                }else{
                    $neednum = intval($config['maxcountall'])-1;
                }
                if($count >= $neednum){
                    Record::setIsfinish($tuanid);
                }else{
                    Record::setNofinish($tuanid);
                }
            }
        
        }
        if ($config['iseditorder']==1 || $myworker['level'] == '1') {
            $data = array(
                    'username' => trim($_P['username']),
                    'mobile' => trim($_P['mobile']),
                );
        }
        if (!empty($_P['uid'])) {
            if ($config['iseditorder']==1 || $myworker['level'] == '1') {
                db_update(t_record, $data, array('uid' => $_P['uid']));
                db_update(t_order, $data, array('uid' => $_P['uid']));
            }
            $data ['chongzhi'] = floatval($_P['chongzhi']);
            $data ['beizhu'] = $_P['beizhu'];
            db_update(t_fans, $data, array('uid' => $_P['uid']));
        }

    return_msg('更新成功');
}
    
if($op == 'refund' && $myworker['level'] == '1') {
    $refundno = getMillisecond();
    //return_msg('暂时关闭,如需退款请联系易宣工作人员');
    if (!empty($theme['jiezhang'])){
        return_msg('此活动已结算,无法退款');
    }
    
    $trade = Order::getPayOrderByRIdZhifude($id);
    if (empty($trade)){
        return_msg('此定单未支付或已退');
    }
    $refundfee = Order::getRealByThemeIdRefund($themeid);
    if ($refundfee>=$theme['refundfee']){
        return_msg('可退'.$theme['refundfee'].'单,授权已用完,请联系工作人员授权!');
    }


    $totalpayfee = Order::getRealByThemeIdnew($themeid) + $theme['chongzhi'] - $trade['realfee'];
    if ($totalpayfee<1){
        return_msg('您的余额不足,无法退款,需先充值再退款');
    }

    $ret = Util::applyrefund($trade,$refundno,$system);
    if ($ret['code']==0){
        Record::deleterecord($system,$themeid,$id);
        $state = db_update(t_order, array('paystate' => -1,'refundtime'=>TIMESTAMP), array('id' => $trade['id']));
        $tuanzhang = Record::getPayedGroupById($id,$themeid);

        $item = Record::getById($id);
        $beizhu = $item['beizhu']. date('m-d H:i') . ' 全额退款 操作:' . $opuser . '<br>';
        $state = db_update(t_record, array('status' => -1,'isrefund'=>1,'refundtime'=>TIMESTAMP,'beizhu'=>$beizhu), array('id' => $id));
        $state = db_update(t_record, array('isfinish' => 0), array('pid' => $id));

        $count = Record::getAttendDetailNumByPId($id);
        db_update( t_record, array("tuannum"=>$count+1), array ('pid' => $id) );
        
        if (empty($tuanzhang)){
            return_msg('退款成功！', $url, 'success');
        }else{
            $sql = "SELECT ord.* FROM " . tablename ( t_record ) . " as ord
                        WHERE  ord.themeid ='{$themeid}' 
                        and (status > 0 or status = -2) and type = 1 and ord.pid='{$id}' 
                        ORDER BY ord.addtime asc ";
            $list = db_find ( $sql,$params);
            if (empty($list)){
                return_msg('退款成功！', $url, 'success');
            }else{
                $state = db_update(t_record, array('type' => 0), array('id' => $list['id']));
                $state = db_update(t_record, array('pid' => $list['id']), array('pid' => $id));
                $state = db_update(t_order, array('ordertype' => 0), array('masterid' => $list['id'],'ordertype' => 1));
                $url = createWebUrl($do,array('op2' => 'scan','id' => $list['id'],'themeid'=>$themeid));
                return_msg('退款成功！'.$list['username'].'成为新团长', $url, 'success');
            }
        }
    }else{
        return_msg($ret['message'], $url, 'info');
    }

}
if($op == 'newtuan'){
    $item = Record::getById($id);
    // $p = array(":openid"=>$item['openid'],":themeid"=>$themeid);
    // $item2 = db_find ( "SELECT * FROM " . tablename ( t_record ) . " 
    //          WHERE openid = :openid and themeid =:themeid and type = 0 and status != 0",$p);
    // if(!empty($item2)){
    //  return_tips('当前粉丝已经是团长了');
    // }
    if(empty($item['status'])){
        return_tips('该定单未付款');
    }
    $data = array(
            'uniacid'  => $_G['mpid'],
            'themeid'  => $themeid,
            'openid'   => $item['openid'],
            'uid'      => $item['uid'],
            'nickname' => $item['nickname'],
            'avatar'   => $item['avatar'],
            'username' => $item['username'],
            'mobile'   => $item['mobile'],
            'addtime'  => TIMESTAMP,
            'fee'      => $config['joinfee'],
            'address'  => $item['address'],
            'datetime' => $item['datetime'],
            'option'   => $item['option'],
            'status'   => -2,
            'fromuid'  => $item['uid'],
            'fopenid'  => $item['openid'],
            'workerid'  => $item['workerid '],
            'pid'      => 0,
            'type'     => 0,
            'uncode'   => $themeid.'-'.TIMESTAMP.rand(1000,1000000)
    );
    $r = $insertid = db_insert(t_record,$data);
    $url = $_G['siteroot']. createMobileUrl('w_order',array("op2"=>"search","searchtxt"=>$item['mobile'],"themeid"=>$themeid));
    return_msg('开新团成功！',$url,'success');
}
if($op == 'uptuanzhang') {    
    $item = Record::getById($id);
    $beizhu = $item['beizhu']. date('m-d H:i') . ' 单买升级为拼团 操作:' . $opuser . '<br>';
    $state = db_update(t_record, array('type' => 0,'beizhu'=>$beizhu), array('id' => $id));
    $url = $_G['siteroot']. createMobileUrl('w_order',array("op2"=>"search","searchtxt"=>$_P['mobile'],"themeid"=>$themeid));
    return_msg('单买升级为拼团成功！',$url,'success');
}
if($op == 'xunifinish') {
    $item = Record::getById($id);
    $beizhu = $item['beizhu']. date('m-d H:i') . ' 设置虚拟成团 操作:' . $opuser . '<br>';
    $state = db_update(t_record, array('xunifinish' =>1,'beizhu'=>$beizhu), array('pid' => $id));
    $url = $_G['siteroot']. createMobileUrl('w_order',array("op2"=>"search","searchtxt"=>$_P['mobile'],"themeid"=>$themeid));
    return_msg('虚拟成团设置成功',$url,'success');
}
if($op == 'unxunifinish') {
    $item = Record::getById($id);
    $beizhu = $item['beizhu']. date('m-d H:i') . ' 取消虚拟成团 操作:' . $opuser . '<br>';
    $state = db_update(t_record, array('xunifinish' =>0,'beizhu'=>$beizhu), array('pid' => $id));
    $url = $_G['siteroot']. createMobileUrl('w_order',array("op2"=>"search","searchtxt"=>$_P['mobile'],"themeid"=>$themeid));
    return_msg('取消虚拟成团设置成功',$url,'success');
}

// if($_G['companyname'] =='飞驰软件'){
//     $return_clicent = get_defined_vars();
return view('/fcworker/fc_orderedit' , $return_clicent);
// }else{
    $return_clicent = get_defined_vars();
return view('/yxworker/w_orderedit' , $return_clicent);
// }
}
}